﻿using ActUtlType64Lib;
using System;
using TYBase;
using TYPLC.PLC;

namespace TYPLC.MX {
    public class MX_PLC : IPLCBase<MXDataItem> {
        ActUtlType64 axActUtlType = new ActUtlType64();
        public int StationNo { get; }
        public MX_PLC(int stationNo) : base() {
            StationNo = stationNo;
        }
        public override bool Connect() {
            try {

                axActUtlType.ActLogicalStationNumber = StationNo;
                var ret = axActUtlType.Open();

                if (ret == 0) {
                    return true;
                }
                return false;
            }
            catch (Exception ex) {
                Log.E("connect error", ex);
                return false;
            }
        }
        public override bool AddressAs(string _strAddress, out MXDataItem data) {
            try {
                data = MXDataItem.FromAddress(_strAddress);
                return true;
            }
            catch (Exception) {
                data = null;
                return false;
            }
        }

        public override bool ReadPri(MXDataItem address, out object value) {
            try {
                var arrDeviceValue = new short[address.count];
                var ret = axActUtlType.ReadDeviceBlock2(address.Address, address.count, out arrDeviceValue[0]);
                if (address.count == 1) {
                    value = arrDeviceValue[0];
                }
                else {
                    value = arrDeviceValue;
                }
                return true;
            }
            catch (Exception ex) {
                value = null;
                return false;
            }
        }

        public override bool WritePri(MXDataItem address, object value) {
            try {
                var arrDeviceValue = new short[1];

                arrDeviceValue[0]= (short)value;
                var ret = axActUtlType.WriteDeviceRandom2(address.Address, 1, ref arrDeviceValue[0]);
                return true;
            }
            catch (Exception ex) {
                return false;
            }

        }
    }


}
